package com.shahe.GirlsDay;

import java.util.Calendar;
import java.util.concurrent.ExecutionException;

import org.json.JSONException;

import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTabHost;
import android.support.v4.app.FragmentTransaction;
import android.view.View;
import android.widget.*;
import android.widget.RadioGroup.OnCheckedChangeListener;

import com.shahe.GirlsDay.fragment.*;
import com.shahe.GirlsDay.util.BasicInfo;
import com.shahe.GirlsDay.util.HttpHelper;
import com.shahe.GirlsDay.util.StaticClass;

public class LogActivity extends FragmentActivity implements
		OnCheckedChangeListener {

	private static final String TAG = LogActivity.class.getSimpleName();
	private FragmentTabHost mTabHost;
	private RadioGroup radioGroup;
	private String date;
	public static BasicInfo oneDayInfo;
	private TextView dateText;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.log);

		findView();

		date = StaticClass.currentDate;
		dateText = (TextView) findViewById(R.id.tv_log_date);
		dateText.setText(date.substring(5));

		if (StaticClass.dayList.indexOf(date) < 0) {
			oneDayInfo = new BasicInfo();
			// StaticClass.DayInfoList.add(oneDayInfo);
			// StaticClass.dayList.add(date);
		} else {
			oneDayInfo = StaticClass.DayInfoList.get(StaticClass.dayList
					.indexOf(date));

		}

		final Button cancelButton = (Button) findViewById(R.id.btn_log_cancel);
		final Button saveButton = (Button) findViewById(R.id.btn_log_save);

		cancelButton.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();
			}
		});

		saveButton.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {

				String temperature = BasicFragment.tempEdit.getText() + "";
				String weight = BasicFragment.weightEdit.getText() + "";
				if (checkNumber(temperature) && checkNumber(weight)
						&& !NoteFragment.note.getText().toString().equals(null)) {
					oneDayInfo.setTemperature(temperature);
					oneDayInfo.setWeight(weight);
					// note
					oneDayInfo.setNote(NoteFragment.note.getText().toString());
				} else {
					warring("Please fill all items!");
				}
				oneDayInfo.setUserid(StaticClass.myInfo.getUserid());
				oneDayInfo.setAdddate(date);

				// save for event fragment
				oneDayInfo.setStayUp(EventFragment.flag_su % 2 + "");
				oneDayInfo.setBath(EventFragment.flag_b % 2 + "");
				oneDayInfo.setColdFood(EventFragment.flag_cf % 2 + "");
				oneDayInfo.setSpicyFood(EventFragment.flag_sf % 2 + "");
				oneDayInfo.setFriedFood(EventFragment.flag_ff % 2 + "");
				oneDayInfo.setCoffeeTea(EventFragment.flag_ct % 2 + "");
				oneDayInfo.setExercise(EventFragment.flag_ex % 2 + "");
				oneDayInfo.setHeavyWork(EventFragment.flag_hw % 2 + "");
				oneDayInfo.setDrink(EventFragment.flag_d % 2 + "");
				oneDayInfo.setKaraoke(EventFragment.flag_kk % 2 + "");
				oneDayInfo.setShopping(EventFragment.flag_sh % 2 + "");
				oneDayInfo.setParty(EventFragment.flag_par % 2 + "");
				oneDayInfo.setExtractTooth(EventFragment.flag_et % 2 + "");

				if (oneDayInfo.getCramps().equals("1")) {
					StaticClass.dayType = 1;
				} else if (oneDayInfo.getCramps().equals("2")) {
					StaticClass.dayType = 2;
				}

				String statusCode;
				try {
					statusCode = new postBasicTask().execute(
							oneDayInfo.toJson().toString()).get();
					if(statusCode.equals(204)||statusCode.equals(200)){
						StaticClass.dayList.add(date);
						StaticClass.DayInfoList.add(oneDayInfo);
						finish();
					}
				} catch (InterruptedException | ExecutionException
						| JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
				
			}
		});

	}

	private void findView() {
		mTabHost = (FragmentTabHost) findViewById(android.R.id.tabhost);
		mTabHost.setup(this, getSupportFragmentManager(), R.id.realtabcontent);
		mTabHost.getTabWidget().setVisibility(View.GONE); // ����ϵͳ��TabWidget

		mTabHost.addTab(mTabHost.newTabSpec("basic").setIndicator("Basic"),
				BasicFragment.class, null);

		mTabHost.addTab(mTabHost.newTabSpec("symptom").setIndicator("Symptom"),
				SymptomFragment.class, null);
		mTabHost.addTab(mTabHost.newTabSpec("event").setIndicator("Event"),
				EventFragment.class, null);

		mTabHost.addTab(mTabHost.newTabSpec("note").setIndicator("Note"),
				NoteFragment.class, null);

		// mTabHost.setOnTabChangedListener(this);
		mTabHost.setCurrentTabByTag("basic");
		((RadioButton) findViewById(R.id.radio_basic)).setChecked(true);

		radioGroup = (RadioGroup) findViewById(R.id.radiogroup);
		radioGroup.setOnCheckedChangeListener(this);
	}

	@Override
	public void onCheckedChanged(RadioGroup group, int checkedId) {
		FragmentManager fm = getSupportFragmentManager();
		BasicFragment basicFragment = (BasicFragment) fm
				.findFragmentByTag("basic");
		SymptomFragment symptomFragment = (SymptomFragment) fm
				.findFragmentByTag("symptom");
		EventFragment eventFragment = (EventFragment) fm
				.findFragmentByTag("event");
		NoteFragment noteFragment = (NoteFragment) fm.findFragmentByTag("note");

		FragmentTransaction ft = fm.beginTransaction();

		// ** Detaches the androidfragment if exists */
		if (basicFragment != null)
			ft.detach(basicFragment);

		if (symptomFragment != null)
			ft.detach(symptomFragment);

		if (eventFragment != null)
			ft.detach(eventFragment);

		if (noteFragment != null)
			ft.detach(noteFragment);

		// if (moreFragment != null)
		// ft.detach(moreFragment);

		switch (checkedId) {
		case R.id.radio_basic:
			if (basicFragment == null) {
				/** Create AndroidFragment and adding to fragmenttransaction */
				ft.add(R.id.realtabcontent, new BasicFragment(), "basic");
			} else {
				/**
				 * Bring to the front, if already exists in the
				 * fragmenttransaction
				 */
				ft.attach(basicFragment);
			}
			mTabHost.setCurrentTabByTag("basic");

			break;
		case R.id.radio_symptom:
			if (symptomFragment == null) {
				ft.add(R.id.realtabcontent, new SymptomFragment(), "symptom");
			} else {
				ft.attach(symptomFragment);
			}
			mTabHost.setCurrentTabByTag("symptom");
			break;
		case R.id.radio_event:
			if (eventFragment == null) {
				ft.add(R.id.realtabcontent, new EventFragment(), "event");
			} else {
				ft.attach(eventFragment);
			}
			mTabHost.setCurrentTabByTag("event");
			break;
		case R.id.radio_note:
			if (noteFragment == null) {
				ft.add(R.id.realtabcontent, new NoteFragment(), "note");
			} else {
				ft.attach(noteFragment);
			}
			mTabHost.setCurrentTabByTag("note");
			break;

		}
	}

	public boolean checkNumber(String str) {
		if (str.matches("^\\d+?")) {
			return true;
		} else if (str.equals(null)) {
			Toast.makeText(this, "null", Toast.LENGTH_LONG).show();
			return false;
		} else {
			// warring("format error");
			Toast.makeText(this, "format error", Toast.LENGTH_LONG).show();
			return false;
		}
	}

	public void warring(String str) {
		Toast.makeText(this, str, Toast.LENGTH_LONG).show();
	}

	private class postBasicTask extends AsyncTask<String, String, String> {

		protected String doInBackground(String... strings) {
			return HttpHelper.postBasic(strings[0]) + "";
		}

		protected void onPostExecute(String result) {
			super.onPostExecute(result);
		}

	}

}
